

package io.lkt.modules.job.task;

import io.lkt.modules.sys.entity.BArticleInfoEntity;
import io.lkt.modules.sys.service.BArticleInfoService;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.util.Date;
import io.netty.util.Timeout;
import io.netty.util.Timer;
import io.netty.util.TimerTask;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 *
 * testTask为spring bean的名称
 *
 * @author xss dustwas@163.com
 */
@Component("testTask")
public class TestTask extends Thread implements ITask  {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private BArticleInfoService bArticleInfoService;

    public void run(){
        //编写自己的线程代码
        System.out.println(Thread.currentThread().getName());
    }
    @Override
    public void run(String params){
        try {

            String host = InetAddress.getLocalHost().getHostAddress();

            if (!host.contains("192.168.5")){

                return;
            }
        } catch (Exception e){

            e.printStackTrace();
        }

        CountDownLatch countDownLatch = new CountDownLatch(8);

        for (int i=0; i<8; i++) {

            Thread thread = new Thread(new Work2(countDownLatch));
            thread.setName(""+(i+1));
            thread.start();
            countDownLatch.countDown();
        }
    }

    public void insetArticle(String content){
        try {
            JSONObject jsonObject = JSONObject.fromObject(content);
            String contents = jsonObject.get("data").toString();
            String code=jsonObject.get("code").toString();
            if(code.equals("1")){
                logger.info("标题存在关键字。");
                return;
            }else if (code.equals("2")) {
                logger.info("文章内容过短。");
                return;
            } else if (code.equals("3")) {
                logger.info("文章内容过短。");
                return;
            } else if (code.equals("4")) {
                logger.info( "文章可能涉嫌违规");
                return;
            } else if (code.equals("5")) {
                logger.info( "段落删除异常");
                return;
            } else if (code.equals("6")) {
                logger.info( "其他异常");
                return;
            }
            jsonObject = JSONObject.fromObject(contents);
            BArticleInfoEntity articleInfo = new BArticleInfoEntity();
            if (jsonObject.get("article_title").toString() == null) {
                return;
            }
            int article_brand_id = Integer.parseInt(jsonObject.get("article_brand_id").toString());
            int article_type_id = Integer.parseInt(jsonObject.get("article_type_id").toString());
            String brandId=article_brand_id==0?null: String.valueOf(article_brand_id);
            int total=bArticleInfoService.titleTotal(jsonObject.get("article_title").toString(),brandId);
            if(total!=0){
                logger.error("文章已存在");
                System.out.println(article_brand_id+">>>"+article_type_id+">>>"+jsonObject.get("article_title").toString());
                return;
            }
            articleInfo.setArticleTitle(jsonObject.get("article_title").toString());
            articleInfo.setArticleImgUrl(jsonObject.get("article_img_url").toString());
            articleInfo.setArticleContent(jsonObject.get("content").toString());
            articleInfo.setArticleDesc(jsonObject.get("article_brief").toString());
            articleInfo.setThirdArticleSource(jsonObject.get("third_article_source").toString());
            articleInfo.setWxArticlePubTime(jsonObject.get("wx_article_pub_time").toString());
            articleInfo.setArticleHotScore(Integer.parseInt(jsonObject.get("article_hot_score").toString()));
            articleInfo.setCreateTime(new Date());
            articleInfo.setArticleSource(1);
            articleInfo.setArticleStatus(1);
            articleInfo.setSpiderProcessStatus(1);
            articleInfo.setArticleVersionNum(2);
            if (article_brand_id != 0) {
                articleInfo.setArticleBrandId(article_brand_id);
            } else if(article_type_id!=0){
                articleInfo.setArticleTypeId(Integer.parseInt(jsonObject.get("article_type_id").toString()));
            }else{
                return;
            }
            bArticleInfoService.save(articleInfo);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
    }

    class Work2 implements Runnable {

        private final CountDownLatch countDownLatch;

        public Work2(CountDownLatch countDownLatch) {
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            try {
                /**
                 *
                 */
                countDownLatch.await();
                HttpClient httpClient = HttpClientBuilder.create().build();
                HttpPost post = new HttpPost("http://192.168.5.3:8888/spiderArticleDesc/");
                String json="{\"data_id\":"+Thread.currentThread().getName()+"}";
                StringEntity postingString = new StringEntity(json);// json传递
                post.setEntity(postingString);
                post.setHeader("Content-type", "application/json");
                Timer timer = new HashedWheelTimer();
                timer.newTimeout(new TimerTask() {
                    public void run(Timeout timeout) throws Exception {
                HttpResponse response = httpClient.execute(post);
                String content = EntityUtils.toString(response.getEntity());
                insetArticle(content);
                    }
                }, 3, TimeUnit.SECONDS);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
